package cn.chendd.session;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

public class SessionListServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        HttpSession session = req.getSession();
        String sessionId = session.getId();
        Enumeration<String> names = session.getAttributeNames();
        StringBuilder json = new StringBuilder();
        json.append("{");
        json.append("\"portId\": \"" + req.getServerPort() + "\",");
        json.append("\"list\" : [");
        boolean flag = false;
        while(names.hasMoreElements()){
            String name = names.nextElement();
            Object value = session.getAttribute(name);
            json.append("{\"name\":\"" + name + "\", \"value\":\"" + value + "\"},");
            flag = true;
        }
        if(flag){
            json.deleteCharAt(json.length() - 1);
        }
        json.append("]");
        json.append(",\"sessionId\": \"" + sessionId + "\"");
        json.append("}");

        resp.setContentType("text/html; charset=utf-8");
        resp.setCharacterEncoding("utf-8");

        PrintWriter out = resp.getWriter();
        out.write(json.toString());
        out.flush();
        out.close();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req , resp);
    }

    private static final long serialVersionUID = 2878267318695777395L;
}

// end::class[]
